// 引入express
const express = require("express");
// 引入cors插件
const cors = require("cors");
// 引入body-parser中间件
const bodyParser = require("body-parser"); //解析参数
// 创建服务器
const app = express();
// 创建路由
const router = express.Router();
// 引入jwt token工具
const JwtUtil = require("./jwt");
const path=require("path");
// app.use(cors);//解决跨域问题
// 设置跨域和相应数据格式
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, mytoken");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Authorization");
  res.setHeader("Content-Type", "application/json;charset=utf-8");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
  );
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  if (req.method == "OPTIONS") res.sendStatus(200);
  /*让options请求快速返回*/ else next();
});

app.use(bodyParser.json()); //json请求
app.use(bodyParser.urlencoded({ extended: false })); //表单请求


//静态文件存放目录
app.use(express.static(path.join(__dirname + "")));
// app.use(function (req, res, next) {
//   // 这里把登陆和注册请求去掉了，其他的多有请求都需要进行token校验
//   if (req.url != "/api/user/userlogin" && req.url != "/api/user/addUser") {
//     let token = req.headers.token;
//     let jwt = new JwtUtil(token);
//     let result = jwt.verifyToken();
//     // 如果考验通过就next，否则就返回登陆信息不正确
//     if (result == "err") {
//       console.log(result);
//       res.send({ status: 403, msg: "登录已过期,请重新登录" });
//       // res.render('login.html');
//     } else {
//       next();
//     }
//   } else {
//     next();
//   }
// });

const login = require("./route/login");
const user = require("./route/user");
const category = require("./route/category");
const upload = require("./route/upload")
const book = require("./route/book")
const shopcart = require("./route/shopcart");
const address = require("./route/address");
const order = require("./route/order")
const statistics = require("./route/statistics")
// 前台路由
app.use("/api/user", login);
app.use("/api/upload", upload)
app.use("/api/book", book)
app.use("/api/shopcart",shopcart)
app.use('/api/address',address)
app.use('/api/order',order)

// 后台管理路由
app.use("/api/admin", login);
app.use("/api/user", user);
app.use("/api/category", category);
app.use("/api/statistics", statistics);


// 监听端口
app.listen(3000, () => console.log("服务器启动在3000端口"));
